package cn.scnu.service.impl;

import cn.scnu.mapper.WArchivesStorageMapper;
import cn.scnu.model.dto.GrowthRateDTO;
import cn.scnu.model.dto.MonthCountDTO;
import cn.scnu.model.dto.XmlxCountDTO;
import cn.scnu.model.dto.YearCountDTO;
import cn.scnu.service.IWarchivesStorageService;
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author hqz
 * @className WarchivesStorageServiceImpl
 * @createTime 2024年11月22日 16:20:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
@DS("master_1")
public class WarchivesStorageServiceImpl implements IWarchivesStorageService {

    private final WArchivesStorageMapper mapper;

    @Override
    public List<XmlxCountDTO> getXmlxCount() {
        return mapper.getXmlxCount();
    }

    @Override
    public Long getXmCount() {
        return mapper.selectCount(null);
    }

    @Override
    public List<MonthCountDTO> getMonthCount(Integer year, String czg) {
        List<MonthCountDTO> monthCounts = mapper.getMonthCount(year, czg);
        Map<Integer, MonthCountDTO> monthCountMap = monthCounts.stream()
                .collect(Collectors.toMap(MonthCountDTO::getMonth, dto -> dto));

        List<MonthCountDTO> result = new ArrayList<>();
        for (int month = 1; month <= 12; month++) {
            result.add(monthCountMap.getOrDefault(month, new MonthCountDTO(month, 0)));
        }
        return result;
    }

    @Override
    public List<GrowthRateDTO> getYearGrowthRate(String czg) {
        List<YearCountDTO> yearGrowthRate = mapper.getYearGrowthRate(czg);
        List<GrowthRateDTO> growthRates = new ArrayList<>();

        for (int i = 1; i < yearGrowthRate.size(); i++) {
            YearCountDTO currentYear = yearGrowthRate.get(i);
            YearCountDTO previousYear = yearGrowthRate.get(i - 1);

            if (currentYear.getYear() != null && previousYear.getYear() != null) {
                double growthRate = ((double) currentYear.getCount() - previousYear.getCount()) / previousYear.getCount() * 100;
                growthRates.add(new GrowthRateDTO(currentYear.getYear(), growthRate));
            }
        }

        return growthRates;
    }

}
